import { ObjectID } from "bson";
import e from "express";
import { is_friend } from '../models/friend_list';
import { Db } from "../common";

import auth, { AuthRequest } from "../middles/auth";
import { message_list, message_list_api, user } from "../models/typeinterface";
import { sessionCreate, sessionSet } from "../session/sess";
var router = e.Router();

/* GET home page. */

//验证是否登录
router.use((req,res,next)=>auth(<AuthRequest>req,res,next))

router.get('/', function(req, res, next) {
  res.render('index', { title: 'mini-chat' });
});

router.get("/login", async function (req, res, next) {
  if (!req.query["user"] || !req.query["pwd"]) {
    res.json({
      status:0,
      token: "",
      info:"参数错误"
    })
    return 
  }
  let doc =await (await Db()).collection("user").findOne({
    user:req.query["user"].toString(),
    pwd:req.query["pwd"].toString()
  })
  if (doc['online_state'] == 1) {
    res.json({
      status: 0,
      token: "",
      info: "账号已在线"
    });
    return 
  }
  if (doc) {
    let token = sessionCreate()
    delete doc['online_state']
    sessionSet(token, "user", doc)
    res.json({
      status:1,
      token: token,
      nickname: doc.name,
      id:doc._id.toString(),
      info:""
    })
    return 
  } else {
    res.json({
      status:0,
      token: "",
      info:"账号或密码错误"
    })
    return 
  }
})

//申请
router.get("/invite", async function (req, res, next) {
  let authreq = <AuthRequest>req
  let acceptor = ""
  if (req.query['acceptor']) {
    acceptor=req.query['acceptor'].toString()
  }
  if (!acceptor) {
    res.json({
      status: 0,
      info:"错误参数"
    })
    return 
  }
  if (await is_friend(authreq.user._id, acceptor)) {
    res.json({
      status: 0,
      info:"已经是好友了"
    })
    return 
  }

  let last = await (await Db()).collection("accept_list").findOne({
    inviter: authreq.user._id,
    acceptor: acceptor,
    state: 0,
  });
  if (last) {
    res.json({
      status: 0,
      info: "已经申请过了，请耐心等待"
    });
    return; 
  }

  let result = await (await Db()).collection("accept_list").insertOne({
    inviter: authreq.user._id,
    acceptor: acceptor,
    state: 0,
    deny_reason: "",
    add_time:new Date()
  })
  if (result && result.insertedId) {
    res.json({
      status: 1,
      info:"suceess"
    })
    return 
  } else {
    res.json({
      status: 0,
      info:"申请失败"
    })
    return 
  }
})

//拒绝
router.get("/deny", async function (req, res, next) {
  let authreq = <AuthRequest>req
  
  let accept_id = ""
  if (req.query["acceptid"]) {
    accept_id = req.query["acceptid"].toString()
  }
  
  let deny_reason = "拒绝"
  if (req.query["deny_reason"]) {
    deny_reason = req.query["acceptid"].toString()
  }

  let result = await (await Db()).collection("accept_list").findOne({
    _id:new ObjectID(accept_id)
  })
  if (!result) {
    res.json({
      status: 0,
      info:"操作失败"
    })
    return 
  }
  if (result.inviter != authreq.user._id && result.acceptor != authreq.user._id) {
    res.json({
      status: 0,
      info:"操作失败2"
    })
    return 
  }
  if (result.state != 0) {
    res.json({
      status: 0,
      info:"操作失败3"
    })
    return 
  }
  await (await Db()).collection("accept_list").updateOne({
    _id: new ObjectID(accept_id),
  }, {
    $set: {
      state: 2,
      deny_reason:deny_reason
    }
  })
  res.json({
    status: 1,
    info:"操作成功"
  })
  return 

})

//同意
router.get("/accept", async function (req, res, next) {
  let authreq = <AuthRequest>req
  
  let accept_id = ""
  if (req.query["acceptid"]) {
    accept_id = req.query["acceptid"].toString()
  }
  let result = await (await Db()).collection("accept_list").findOne({
    _id:new ObjectID(accept_id)
  })
  if (!result) {
    res.json({
      status: 0,
      info:"操作失败"
    })
    return 
  }
  if (result.inviter != authreq.user._id && result.acceptor != authreq.user._id) {
    res.json({
      status: 0,
      info:"操作失败2"
    })
    return 
  }
  if (result.state != 0) {
    res.json({
      status: 0,
      info:"操作失败3"
    })
    return 
  }
  //接受
  await (await Db()).collection("accept_list").updateOne({
    _id: new ObjectID(accept_id),
  }, {
    $set: {
      state: 1
    }
  })
  if (!await is_friend(authreq.user._id, accept_id)) {
    //添加好友至列表
    await (await Db()).collection("friend_list").insertOne({
        userid: result.inviter,
        friend_userid: result.acceptor,
        state: 1,
        add_time:new Date()
    })
  }
  
  res.json({
    status: 1,
    info:"操作成功"
  })
  return 

})

//寻找好友
router.get("/find", async function (req, res, next) {
  let authreq = <AuthRequest>req
  let keyword = ""
  if (req.query["keyword"]) {
    keyword=req.query["keyword"].toString()
  }
  let list = await (await Db()).collection("user").find({
    name: new RegExp(keyword),
    _id:{$ne:new ObjectID(authreq.user._id)}
  }).limit(100)
  let user_list = []
  await list.forEach((doc) => {
    console.log(doc)
    user_list.push({
      id: doc._id.toString(),
      name: doc.name,
      is_friend:false
    })
  })

  //是否已经是好友
  let f_list = (await Db()).collection("friend_list").find({
    $or: [
        {
          userid: authreq.user._id,
          state:1
        },
        {
          friend_userid: authreq.user._id,
          state:1
        }
    ],
  })
  await f_list.forEach((doc) => {

    let friend_id = ''
    if (doc.userid == authreq.user._id) {
      friend_id=doc.friend_userid
    } else {
      friend_id=doc.userid
    }

    for (let i = 0; i < user_list.length; i++) { 
      if (user_list[i].id == friend_id) {
        user_list[i].is_friend=true
      } else {
        user_list[i].is_friend=false
      }
    }
  })


  res.json({
    status: 1,
    list:user_list
  })
  return 
})

//申请列表
router.get("/accept_list", async function (req, res, next) {
  let authreq = <AuthRequest>req
  let id = authreq.user._id

  let list = (await Db()).collection("accept_list").find({
      $or: [
        {
          inviter: id
        },
        {
          acceptor: id
        }
    ],
  }).sort({add_time:1})
  let list2 = []

  let fid_list = []
  await list.forEach((doc) => {
    let friend_id = ''
    if (doc.inviter == id) {
      friend_id=doc.acceptor
    } else {
      friend_id=doc.inviter
    }
    fid_list.push({
      id:doc._id.toString(),
      friend_id: friend_id,
      state: doc.state,
      deny_reason: doc.deny_reason,
      add_time:doc.add_time
    })
  })


  for (let i = 0; i < fid_list.length; i++){
    let userinfo = await (await Db()).collection("user").findOne({
      _id:new ObjectID(fid_list[i].friend_id)
    })
    var cur =fid_list[i]
    list2.push({
      id:cur.id,
      friend_id: cur.friend_id,
      name: userinfo.name,
      state: cur['state'],
      deny_reason: cur['deny_reason'],
      add_time:cur['add_time']
    })
  }

  res.json({
    status: 1,
    list:list2
  })
  return 
})

//好友列表
router.get("/friend_list", async function (req, res, next) {
  let authreq = <AuthRequest>req
  let id = authreq.user._id

  let list = (await Db()).collection("friend_list").find({
      $or: [
        {
          userid: id,
          state:1
        },
        {
          friend_userid: id,
          state:1
        }
    ],
  }).sort({add_time:1})
  let list2 = []

  let fid_list = []
  await list.forEach((doc) => {
    let friend_id = ''
    if (doc.userid == id) {
      friend_id=doc.friend_userid
    } else {
      friend_id=doc.userid
    }
    fid_list.push(friend_id)
  })


  for (let i = 0; i < fid_list.length; i++){
    let userinfo = await (await Db()).collection("user").findOne({
      _id:new ObjectID(fid_list[i])
    })
    list2.push({
      friend_id: userinfo._id.toString(),
      name: userinfo.name,
      online_state:userinfo.online_state
    })
  }

  res.json({
    status: 1,
    list:list2
  })
  return 
})

router.get("/message", async function (req, res, next) {
  let authreq = <AuthRequest>req
  let id = authreq.user._id
  let friend_id = req.query["friendid"]

  let time = new Date();
  time.setHours(0, 0, 0, 0);
  
  //更新发给id的信息为已读
  await (await Db()).collection("message_list").updateMany({
    sender: friend_id,
    receiver: id
  }, {
    $set: {
      is_read:1
    }
  });

  let list = (await Db()).collection("message_list").find({
    $or: [{
      sender: id,
      receiver: friend_id
    },
    {
      sender: friend_id,
      receiver: id
    }],
    // add_time: {
    //   $gte:time
    // }
  }).sort({ add_time: -1 }).limit(200);//显示最近200条
  let list2 = [];
  await list.forEach((doc) => {
    list2.push({
      sender: doc.sender,
      receiver: doc.receiver,
      msg: doc.msg,
      is_read: doc.is_read,
      add_time: doc.add_time,
    });
  })
  list2 = list2.reverse();

  res.json({
    status: 1,
    list:list2
  })
  return 
})

//消息列表
router.get("/message_list", async function (req, res, next) {
  let authreq = <AuthRequest>req
  let id = authreq.user._id
  let list = (await Db()).collection("message_list").find({
    $or: [{
      sender: id,
    },
    {
      receiver: id
    }]
  }).sort({ add_time: -1 })
  let list2:message_list[] = [];

  //  friend_id => add_time last msg
  let map2 = <Map<string,message_list>>{};
  await list.forEach((doc) => { 
    let obj = <message_list_api>{
      _id:doc._id,
      sender: doc.sender,
      receiver: doc.receiver,
      msg: doc.msg,
      is_read: doc.is_read,
      add_time: doc.add_time,
      name:""
    }
    if (doc.sender == id) {
      if (!map2[doc.receiver]) {
        map2[doc.receiver] = obj
      }
    } else {
      if (!map2[doc.sender]) {
        map2[doc.sender] = obj
      }
    }
  })
  for (let fid in map2) {
    let userinfo = await (await Db()).collection("user").findOne({
      _id:new ObjectID(fid)
    })
    map2[fid].name = userinfo.name;
    list2.push(map2[fid])
  }
  res.json({
    status: 1,
    list:list2
  })
  return 
})

//注册账号
router.post("/reg", async function (req, res, next) {
  if (!req.body["user"] || !req.body["pwd"] || !req.body["name"]) {
    res.json({
      status: 0,
      info:"参数错误"
    })
    return
  }
  let result2 = await (await Db()).collection("user").findOne({
    name:req.body["name"].toString()
  })
  if (result2) {
    res.json({
      status: 0,
      info:"用户名已存在"
    })
    return
  }
  let result3 = await (await Db()).collection("user").findOne({
    user:req.body["user"].toString()
  })
  if (result3) {
    res.json({
      status: 0,
      info:"账号已存在"
    })
    return
  }
  let result = await (await Db()).collection("user").insertOne(<user>{
    user:req.body["user"].toString(),
    pwd: req.body["pwd"].toString(),
    name: req.body["name"].toString(),
    online_state:0,
    add_time:new Date()
  })
  
  if (result.insertedId) {
    res.json({
      status: 1,
      id: result.insertedId.toString(),
      info:"注册成功"
    })
    return 
  } else {
    res.json({
      status: 0,
      info:"注册失败"
    })
    return 
  }
})

export default router;
